package easybooking.clients.gui.editor;

import javax.swing.text.*;

/**
 * @author Tim Schröder
 * This class is used to limit text fields to a specific number of characters
 * http://www.tutorials.de/java/223804-jtextfield-anzahl-zeichen-begrenzen.html
 */
public class JTextFieldLimit extends PlainDocument {

    private int limit;
// optional uppercase conversion
    private boolean toUppercase = false;

    /**
     * Limits the text field
     */
    public JTextFieldLimit() {
        super();
    }

    /**
     * Limits the text field
     * @param limit number of characters to which the field shoudld be limited
     */
    public JTextFieldLimit(int limit) {
        super();
        this.limit = limit;
    }

    /**
     * Limits the text field
     * @param limit limit number of characters to which the field shoudld be limited
     * @param upper only allow upper case
     */
    public JTextFieldLimit(int limit, boolean upper) {
        super();
        this.limit = limit;
        toUppercase = upper;
    }

    /**
     * Insterts the string
     * @param offset offstet of the input
     * @param str the string which sould be insered
     * @param attr attribute set
     * @throws BadLocationException
     */
    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str == null) {
            return;
        }

        if ((getLength() + str.length()) <= limit) {
            if (toUppercase) {
                str = str.toUpperCase();
            }
            super.insertString(offset, str, attr);
        }
    }
}
